package com.hermes.action.login;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.hermes.biz.common.util.login.CorpLoginUtil;
import com.hermes.biz.common.util.string.StringUtil;
import com.hermes.common.action.BaseAction;
import com.hermes.common.util.ParameterParserUtil;

public class CorpQQLoginProcessAction  extends BaseAction{
	
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(CorpQQLoginProcessAction.class);
	private static CorpLoginUtil clu = new CorpLoginUtil();
	
	@Override
	public String execute() throws IOException {
		
		String codeRes = ParameterParserUtil.getParameter("code");

		if(StringUtil.isNotBlank(codeRes)){
			String getATRes = executeSend(clu.qqGetAccessTokenUrl,"code="+codeRes);
			logger.error(getATRes);
			String[] resArray = getATRes.split("&");
			logger.error(resArray[0]);
			String getOpenIdStr = executeSend(clu.qqGetOpenIdUrl,resArray[0]);
			logger.error(getOpenIdStr);
			getOpenIdStr = getOpenIdStr.substring(9, getOpenIdStr.length()-3);
			System.out.println(getOpenIdStr);
			JSONObject jo = JSONObject.fromObject(getOpenIdStr);
			String openId = jo.getString("openid");
			String getUserParamStr = "access_token="+resArray[0]+"&oauth_consumer_key=100316154&openid="+openId;
			String userInfoJsonStr = executeSend(clu.qqGetUserInfoUrl,getUserParamStr);
			logger.error(userInfoJsonStr);  
			JSONObject userInfo = JSONObject.fromObject(userInfoJsonStr);
			String userName = userInfo.getString("nickname");
			session.put("userName", userName);
	        HttpServletResponse response = ServletActionContext.getResponse();
			response.sendRedirect("/index.htm");
		}
		else{
			//进这里是傻逼
		}
		return null;
	}
	
	public  String executeSend(String url ,String param){
		try{
			
			String sendURL = url+param;
			HttpClient hc = new DefaultHttpClient();
			HttpGet httpget= new HttpGet(sendURL);  
			HttpResponse response =hc.execute(httpget);
	        HttpEntity entity = response.getEntity();  
	        System.out.println("<< Response: " + response.getStatusLine());  
	        if (entity != null) {  
		        return EntityUtils.toString(entity);
	        } 
		}
		catch(Exception e){
			logger.error(e);
		}
		return "";

	}

}
